<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                 label-width="80px">
            <el-form-item label="商品类目：" prop="classifyId" label-width="80">
                <el-select v-model="queryParams.classifyId" placeholder="请选择商品发布类目" @change="changeClass" clearable>
                    <el-option
                        v-for="classify in classifyList"
                        :key="classify.classifyId"
                        :label="classify.classifyName"
                        :value="classify.classifyId"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="所属村社：" prop="communityId" label-width="80">
                <el-select v-model="queryParams.communityId" placeholder="请选择所属村社" @change="changeCommunity" :disabled="form.communityIdShow" clearable>
                    <el-option
                        v-for="community in communityList"
                        :key="community.communityId"
                        :label="community.communityName"
                        :value="community.communityId"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="状态:" prop="status" >
                <el-select v-model="queryParams.status" placeholder="是否上架" clearable>
                    <el-option
                        v-for="dict in dict.type.sys_on_off"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="商品名称：" prop="title" label-width="80">
                <el-input
                    v-model="queryParams.title"
                    placeholder="请输入商品名称"
                    clearable
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleAdd"
                    v-hasPermi="['business:goods:add']"
                >新增
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="danger"
                    plain
                    icon="el-icon-document-copy"
                    size="mini"
                    @click="handleBatch"
                    v-hasPermi="['business:goods:batchUpdate']"
                >批量修改发放信息
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="danger"
                    plain
                    icon="el-icon-document-copy"
                    size="mini"
                    @click="handleBathAudit"
                    v-hasPermi="['business:goods:batchAudit']"
                >批量审核
                </el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="goodsList" @selection-change="handleSelectionChange" border :fit="true">
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column label="村社" align="center" prop="communityName"/>
            <el-table-column label="类目" align="center" prop="classifyName"/>
            <el-table-column label="商品名" align="left" prop="title" width="200" :show-overflow-tooltip="true"/>
            <el-table-column label="原价" align="center" prop="originalPrice"/>
            <el-table-column label="兑换数量" align="center" prop="quantity"/>
            <el-table-column label="消耗积分" align="center" prop="exchangeNum"/>
            <el-table-column label="库存" align="center" prop="stock">
                <template slot-scope="scope">
                    <el-tag type="success" v-if="scope.row.stockType==0">不限</el-tag>
                    <el-tag type="danger" v-if="scope.row.stockType==1">{{scope.row.stock}}</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="上架日期" align="center" prop="startTime" width="200">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span> ~ <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
                </template>
            </el-table-column>
            <el-table-column label="发放日期" align="center" prop="startTime" width="200">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.exchangeStartTime, '{y}-{m}-{d}') }}</span> ~ <span>{{ parseTime(scope.row.exchangeEndTime, '{y}-{m}-{d}') }}</span>
                </template>
            </el-table-column>
            <el-table-column label="兑换地址" align="center" prop="exchangeAddress" width="120px" :show-overflow-tooltip="true"/>
            <el-table-column label="上下架" align="center" prop="status">
                <template slot-scope="scope">
                    <el-switch
                        v-model="scope.row.status"
                        active-value="0"
                        inactive-value="1"
                        @change="handleStatusChange(scope.row)"
                    ></el-switch>
                </template>
            </el-table-column>
            <el-table-column label="审核" align="center" prop="audit">
                <template slot-scope="scope">
                    <el-tag type="success" v-if="scope.row.audit==0">待镇审核</el-tag>
                    <el-tag type="danger" v-if="scope.row.audit==1">已审核</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="170">
                <template slot-scope="scope">
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-view"
                        @click="handleRead(scope.row)"
                        v-hasPermi="['business:goods:edit']"
                    >查看
                    </el-button>
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-check"
                        @click="handleUpdate(scope.row)"
                        v-hasPermi="['business:goods:edit']"
                    >修改
                    </el-button>
                    <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)" v-if="auditSubmitShow && scope.row.audit==='0' ">
                        <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item command="handleAudit" icon="el-icon-circle-check"
                                              v-hasPermi="['business:goods:edit']">审核
                            </el-dropdown-item>

                        </el-dropdown-menu>
                    </el-dropdown>
                </template>
            </el-table-column>
        </el-table>

        <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
        />

        <!-- 添加或修改商品列表对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="100px">
                <el-form-item label="商品类目：" prop="classifyId">
                    <el-select v-model="form.classifyId" placeholder="请选择商品发布类目" @change="changeClass">
                        <el-option
                            v-for="classify in classifyList"
                            :key="classify.classifyId"
                            :label="classify.classifyName"
                            :value="classify.classifyId"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="所属村社：" prop="communityId">
                    <el-select v-model="form.communityId" placeholder="请选择所属村社" @change="changeCommunity" :disabled="form.communityIdShow">
                        <el-option
                            v-for="community in communityList"
                            :key="community.communityId"
                            :label="community.communityName"
                            :value="community.communityId"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="商品图片：" prop="imgUrl">
                    <el-col :span="20">
                        <image-upload v-model="form.imgUrl" :limit="1"/>
                    </el-col>
                </el-form-item>
                <el-form-item label="商品名称：" prop="title">
                    <el-col :span="20">
                        <el-input v-model="form.title" placeholder="请输入商品名称"/>
                    </el-col>
                </el-form-item>
                <el-form-item label="商品原价：" prop="originalPrice">
                    <el-col :span="20">
                        <el-input v-model="form.originalPrice" placeholder="请输入商品原价"/>
                    </el-col>
                </el-form-item>
                <el-form-item label="兑换数量：" prop="quantity">
                    <el-col :span="20">
                    <el-input v-model="form.quantity" placeholder="请输入兑换一次发放商品的数量"/>
                    </el-col>
                </el-form-item>
                <el-form-item label="兑换积分：" prop="exchangeNum">
                    <el-col :span="20">
                    <el-input v-model="form.exchangeNum" placeholder="请输入需要多少积分才可以兑换"/>
                    </el-col>
                </el-form-item>
                <el-form-item label="库存量：" prop="stock">
                    <el-radio-group v-model="form.stockType">
                        <el-radio :key="type.label" v-for="type in stockTypes" :label="type.label">{{type.name}}</el-radio>
                    </el-radio-group>
                    <el-input v-model="form.stock" placeholder="请输入库存数" style="width: 200px;margin-left: 5px;" v-show="form.stockType==1"/>
                </el-form-item>
                <el-form-item label="上架时间：" prop="startTime">
                    <el-col :span="20">
                        <el-date-picker
                            v-model="activityDate.date"
                            type="datetimerange"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            range-separator="至"
                            start-placeholder="开始时间"
                            end-placeholder="结束时间"
                            :default-time="['00:00:00', '23:59:59']"
                            @change="activityDateFormat"
                        >
                        </el-date-picker>
                    </el-col>
                </el-form-item>
                <el-form-item label="发放日期：" prop="exchangeStartTime">
                    <el-date-picker
                        v-model="exchangeDate.date"
                        type="datetimerange"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        range-separator="至"
                        start-placeholder="预计发放开始时间"
                        :default-time="['00:00:00', '23:59:59']"
                        end-placeholder="预计发放结束时间" @change="exchangeDateFormat">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="发放地址：" prop="exchangeAddress">
                    <el-input v-model="form.exchangeAddress" placeholder="请输入居民统一领取商品地址"/>
                </el-form-item>
                <el-form-item label="商品简介：" prop="descibe">
                    <editor v-model="form.descibe" :min-height="400"/>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="danger" @click="submitForm" v-if="form.goodsId>0 && !formRead">更 新 商 品</el-button>
                <el-button type="primary" @click="submitForm" v-if="form.goodsId==undefined">新 增 商 品</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
        <el-dialog :title="title" :visible.sync="batchOpen" width="800px" append-to-body>
            <el-form ref="form" :model="form" :rules="batchRules" label-width="100px">
                <el-form-item label="上架时间：" prop="startTime">
                    <el-col :span="20">
                        <el-date-picker
                            v-model="activityDate.date"
                            type="datetimerange"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            range-separator="至"
                            start-placeholder="开始时间"
                            end-placeholder="结束时间"
                            :default-time="['00:00:00', '23:59:59']"
                            @change="activityDateFormat"
                        >
                        </el-date-picker>
                    </el-col>
                </el-form-item>
                <el-form-item label="发放日期：" prop="exchangeStartTime">
                    <el-date-picker
                        v-model="exchangeDate.date"
                        type="datetimerange"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        range-separator="至"
                        start-placeholder="预计发放开始时间"
                        end-placeholder="预计发放结束时间"
                        :default-time="['00:00:00', '23:59:59']"
                        @change="exchangeDateFormat">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="发放地址：" prop="exchangeAddress">
                    <el-input v-model="form.exchangeAddress" placeholder="请输入居民统一领取商品地址"/>
                </el-form-item>
                <el-form-item label="批量的商品">
                    <el-checkbox v-model="checked"  @change="handleCheckedTreeNodeAll">全选/全不选
                    </el-checkbox>
                    <el-tree
                        class="tree-border"
                        :data="goodTreeData"
                        show-checkbox
                        default-expand-all
                        ref="listTree"
                        node-key="id"
                        empty-text="加载中，请稍候"
                        :props="defaultProps"
                    ></el-tree>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="danger" @click="submitBatchForm">批 量更 新</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {
    listGoods,
    getGoods,
    addGoods,
    updateGoods,
    changeAuditStatus,
    changeGoodsStatus,
    getGoodsTree, batchGoods,requestBathAudit
} from "@/api/business/goods";
import {listClassify} from "@/api/mall/classify";
import {listCoupon} from "@/api/business/coupon"
import {listCommunity} from "@/api/organization/community";
import {communityPermission, rolesPermission} from "@/utils/ruoyi";
import {treeselect as menuTreeselect} from "@/api/system/menu";
export default {
    name: "Goods",
    dicts:['sys_on_off'],
    data() {
        return {
            checked:false,
            deptCheckStrictly:false,
            defaultProps: {
                children: "children",
                label: "label"
            },
            activityDate:{
                date:[],
            },
            exchangeDate:{
                date:[]
            },
            formRead:false,
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 商品列表表格数据
            goodsList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            batchOpen: false,
            classifyList: {},
            couponList:[],
            communityList:[],
            exchangeType: [{"name": "实物", "label": 0}],//, {"name": "券码", "label": 1}
            stockTypes: [{"name": "不限制", "label": 0}, {"name": "限制", "label": 1}],
            times: [],
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                tenantId: null,
                title: null,
                exchangeType: null,
                quantity: null,
                classifyId: null,
                communityId: null,
                exchangeNum: null,
                stock: null,
                startTime: null,
                endTime: null,
                exchangeAddress: null,
                descibe: null,
                imgUrl: null,
                status: null,
                audit: null,
            },
            goodTreeData :[],
            // 查询参数
            classifyParams: {
                pageNum: 1,
                pageSize: 100
            },
            // 查询参数
            commonVars: {
                pageNum: 1,
                pageSize: 100
            },
            communityVars: {
                pageNum: 1,
                pageSize: 100,
                status:0
            },
            // 表单参数
            form: {},
            auditSubmitShow:false,
            // 表单校验
            rules: {
                classifyId: [{required: true, message: "商品类目不能空", trigger: "blur"}],
                communityId: [{required: true, message: "显示的村社不能空", trigger: "blur"}],
                imgUrl: [{required: true, message: "商品缩略图不能空", trigger: "blur"}],
                title: [{required: true, message: "商品名称不能空", trigger: "blur"}],
                quantity: [{required: true, message: "单次兑换数量不能空", trigger: "blur"}],
                exchangeNum: [{required: true, message: "单次兑换消耗积分数不能空", trigger: "blur"}],
                startTime: [{required: true, message: "商品上架的时间", trigger: "blur"}],
                exchangeStartTime: [{required: true, message: "商品发放的时间", trigger: "blur"}],
                exchangeAddress: [{required: true, message: "商品发放地址不能空", trigger: "blur"}],
                descibe: [{required: true, message: "商品简介不能空", trigger: "blur"}],
                originalPrice: [{required: true, message: "商品原价不能空", trigger: "blur"}],
            },
            batchRules: {
                startTime: [{required: true, message: "商品上架的时间", trigger: "blur"}],
                exchangeStartTime: [{required: true, message: "商品发放的时间", trigger: "blur"}],
                exchangeAddress: [{required: true, message: "商品发放地址不能空", trigger: "blur"}],
            }
        };
    },
    created() {

        this.getList();
        this.setRoles();
        this.getClassifyList();
        this.getCommunityList();
    },
    methods: {
        rolesPermission,
        setRoles(){
            var role = rolesPermission();
            if (role<=1) {
                this.auditSubmitShow = true;
            }
        },
        getMenuTreeselect() {
            menuTreeselect().then(response => {
                this.goodTreeData = response.data;
            });
        },
        handleCheckedTreeNodeAll(value) {
            this.$refs.listTree.setCheckedNodes(value ? this.goodTreeData : []);
            console.log(this.$refs.listTree.getCheckedKeys())
        },
        // 更多操作触发
        handleCommand(command, row) {
            switch (command) {
                //设置审核
                case "handleAudit":
                    this.handleAudit(row);
                    break;
                default:
                    break;
            }
        },
        changeCommunity(raw) {
            for (let communityListElement of this.communityList) { console.log(communityListElement)
                if(communityListElement.communityId==raw) {
                    this.form.communityName = communityListElement.communityName;
                    break;
                }
            }
            console.log(this.form.communityName)
        },
        changeClass(raw) {
            for (let classElement of this.classifyList) {
                if(classElement.classifyId==raw) {
                    this.form.classifyName = classElement.classifyName;
                    break;
                }
            }
            console.log(this.form.classifyName)
        },
        activityDateFormat(picker) {
            this.form.startTime =picker[0].toString();
            this.form.endTime = picker[1].toString();
            console.log("activityTimes")
        },
        exchangeDateFormat(exchange) {
            this.form.exchangeStartTime = exchange[0].toString()
            this.form.exchangeEndTime = exchange[1].toString()
        },
        /** 商品类目 **/
        getClassifyList() {
            listClassify(this.commonVars).then(response => {
                this.classifyList = response.rows;
            });
        },
        getCouponList(){
            listCoupon(this.commonVars).then(response=>{
                this.couponList = response.rows;
            })
        },
        getCommunityList(){
            listCommunity(this.communityVars).then(response=>{
                this.communityList = response.rows;
            })
        },
        /** 查询商品列表列表 */
        getList() {
            this.loading = true;
            listGoods(this.queryParams).then(response => {
                this.goodsList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.batchOpen = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                goodsId: null,
                tenantId: null,
                title: null,
                exchangeType: null,
                quantity: null,
                classifyId: null,
                communityId: null,
                exchangeNum: null,
                stock: null,
                stockType: 0,
                startTime: null,
                endTime: null,
                exchangeStartTime: null,
                exchangeEndTime: null,
                exchangeAddress: null,
                descibe: null,
                imgUrl: null,
                status: null,
                audit: null,
                createBy: null,
                createTime: null,
                updateBy: null,
                updateTime: null
            };

            this.activityDate.date = [];
            this.exchangeDate.date = [];
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.goodsId)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "添加商品";
            this.form.exchangeType = 0;
            this.formRead = false;
            communityPermission(this.form);
        },
        handleBatch: function () {
            this.reset();
            this.batchOpen = true;
            this.title = "批量修改领取信息";
            getGoodsTree({}).then(resp=>{this.goodTreeData = resp.data;})
        },
        handleBathAudit:function () {
            this.$modal.confirm('确认批量审核?').then(function () {
                return requestBathAudit();
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess("批量审核成功");
                this.getList();
            }).catch(() => {
            });
        },
        /** 修改按钮操作 */
        /** 修改按钮操作 */
        handleUpdate(row) {

            this.reset();
            const goodsId = row.goodsId || this.ids
            getGoods(goodsId).then(response => {
                this.form = response.data;
                this.open = true;
                this.title = "修改商品";
                this.activityDate.date.push(this.form.startTime);
                this.activityDate.date.push(this.form.endTime);
                this.exchangeDate.date.push(this.form.exchangeStartTime);
                this.exchangeDate.date.push(this.form.exchangeEndTime);
                thi.formRead = false;
            });
        },
        /** 修改按钮操作 */
        handleRead(row) {
            this.reset();
            this.formRead = true;
            const goodsId = row.goodsId || this.ids
            getGoods(goodsId).then(response => {
                this.form = response.data;
                this.open = true;
                this.title = "查看商品";
                this.activityDate.date.push(this.form.startTime);
                this.activityDate.date.push(this.form.endTime);
                this.exchangeDate.date.push(this.form.exchangeStartTime);
                this.exchangeDate.date.push(this.form.exchangeEndTime);
            });
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (this.form.stockType==1 && (this.form.stock==null || this.form.stock==0 || this.form.stock=="" || this.form.stock==undefined)) {
                       this.$modal.alertError("库存数量不能空");
                       return false;
                    }
                    let tt = this.auditSubmitShow? "":",请等待镇级审核!"
                    if (this.form.goodsId != null) {
                        updateGoods(this.form).then(response => {
                            this.$modal.msgSuccess("修改成功"+tt);
                            this.open = false;
                            this.getList();
                        });
                    }
                    else {

                        addGoods(this.form).then(response => {
                            this.$modal.msgSuccess("新增成功"+tt);
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },
        submitBatchForm() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (this.$refs.listTree.getCheckedKeys().length==0) {
                        this.$modal.msgError("请选择商品");
                        return false;
                    }
                    var data = {
                        "goodsId": this.$refs.listTree.getCheckedKeys(),
                        "exchangeStartTime": this.form.exchangeStartTime,
                        "exchangeEndTime": this.form.exchangeEndTime,
                        "startTime": this.form.startTime,
                        "endTime": this.form.endTime,
                        "exchangeAddress": this.form.exchangeAddress
                    };

                    this.$confirm('确认批量修改领取信息？', '提示', {
                        confirmButtonText: '确认',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(function () {
                        return batchGoods(data);
                    }).then(() => {
                        this.getList();
                        this.$modal.msgSuccess("操作成功");
                        this.reset();
                        this.batchOpen = false;
                    }).catch(action => {
                        //判断是 cancel (自定义的取消) 还是 close （关闭弹窗）
                        if (action === 'cancel') {

                        }
                    });
                }
            });
        },
        /** 审核按钮 */
        handleAudit(row) {
            const goodsIds = row.goodsId || this.ids;
            this.$confirm('确认审核商品' + row.title ,'提示',{
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(function () {
                return changeAuditStatus(goodsIds,1);
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess("操作成功");
            }).catch(action => {
                //判断是 cancel (自定义的取消) 还是 close （关闭弹窗）
                if (action === 'cancel'){

                }
            });
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download('business/goods/export', {
                ...this.queryParams
            }, `goods_${new Date().getTime()}.xlsx`)
        },
        handleStatusChange(row) {
            let text = row.status === "0" ? "上架" : "下架";
            this.$modal.confirm('确认要' + text + row.title + '这个商品嘛？').then(function () {
                return changeGoodsStatus(row.goodsId, row.status);
            }).then(() => {
                this.$modal.msgSuccess(text + "成功");
            }).catch(function () {
                row.status = row.status === "0" ? "1" : "0";
            });
        },
    }
};
</script>
